package spittr.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import spittr.Spitter;
import spittr.Spittle;
import spittr.data.SpitterRepository;
import spittr.exception.SpitterNotFoundException;

import javax.validation.Valid;


@Controller
@RequestMapping("/spitter")
public class SpitterController {


    private SpitterRepository spitterRepository;

    @Autowired
    public SpitterController(SpitterRepository spitterRepository) {
        this.spitterRepository = spitterRepository;
    }

    /**
     * 打开注册页
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String showRegFormForm(Model model){
         model.addAttribute("spitter",new Spitter());
         return "registerForm";
    }

    /**
     * 处理注册请求,并跳转至个人信息页
     * (在重定向请求之间利用Session传递参数,放入RedirectAttributes中的属性，重定向之后并不会消失)
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String processRegistration(@Valid Spitter spitter, Errors errors, @RequestParam("profilePicture") MultipartFile multipartFile, RedirectAttributes model){
        if(errors.hasErrors()){
            return "registerForm";
        }
        System.out.println(multipartFile);
       // multipartFile.transferTo();//保存文件
        spitterRepository.save(spitter);
        //forward,redirect
        model.addAttribute("username",spitter.getUsername());
        model.addFlashAttribute("spitter",spitter);
        return "redirect:/spitter/{username}";
    }


    /**
     * 展示个人信息
     * @param username
     * @param model
     * @return
     */
    @RequestMapping(value = "/{username}",method = RequestMethod.GET)
    public String showSpitterProfile(@PathVariable  String username, Model model) {

        if(!model.containsAttribute("spitter")) {
            Spitter spitter = spitterRepository.findByUsername(username);
            model.addAttribute("spitter", spitter);
        }
        return "profile";
    }





    /**
     * SpitterNotFoundException处理器，处理该类中全部抛出SpitterNotFoundException异常的方法
     * @return
     */
    @ExceptionHandler({SpitterNotFoundException.class})
    public String handleNotSpitter(){
        return "error/spitterNotFound";
    }

}
